package JUC_stady;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;

/**
 * Project: tobe-better-coder
 * Package: JUC_stady
 * CompletableFuture四个获取实例的方法，如果参数不传线程池，就会用他自己的默认线程，默认线程是守护线程，这时候main线程一结束，则守护线程不管任务完成与否，也会立马结束
 *
 * @author : Mr.xu
 * @date : 2023/3/1 22:53
 */
public class CompletableFutureTest {

    public static void main(String[] args) {

        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        try {
            CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> {
                int result = ThreadLocalRandom.current().nextInt(10);
                result = 6;
                System.out.println(Thread.currentThread().getName() + "正在执行任务");
                System.out.println(Thread.currentThread().getName() + "是否是守护线程" + Thread.currentThread().isDaemon());
                System.out.println("获取了计算结果" + result);
                if (result > 5) {
                    int a = result / 0;
                }
                try {
                    Thread.sleep(result * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return result;
            }, threadPool).whenComplete((v, e) -> {
                System.out.println("副线任务完成，获取最终结果" + v * v);
            }).exceptionally(e -> {
                e.printStackTrace();
                System.out.println("线程执行任务失败");
                return null;
            });

            System.out.println(Thread.currentThread().getName() + "主线程处理主要任务");
            int a = 10 / 0;
        } catch (Exception e) {
            System.out.println("线程执行任务失败111");
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }

    public static void method1() {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        CompletableFuture completableFuture = CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "正在执行任务");
            try {
                Thread.sleep(5000);
                int q = 10 / 0;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, threadPool).whenComplete((unused, throwable) -> {
            System.out.println("任务失败了");
        });
    }
}